<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="108px"
    >
      <el-form-item label="采购事项名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入采购事项名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="采购类型" prop="purchaseType">
        <el-select
          v-model="queryParams.purchaseType"
          placeholder="请选择采购类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PURCHASE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预算归属部门" prop="budgetDepartmentId">
        <el-select
          v-model="queryParams.budgetDepartmentId"
          placeholder="请选择预算归属部门"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="dict in DeptPageList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="需求使用部门" prop="applicationDepartmentId">
        <el-select
          v-model="queryParams.applicationDepartmentId"
          placeholder="请选择需求使用部门"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="dict in DeptPageList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:purchase-plan:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:purchase-order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          @click="handleDeleteList(selectionList.map((item) => item.id))"
          v-hasPermi="['erp:purchase-order:delete']"
          :disabled="selectionList.length === 0"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column width="60" label="选择" type="selection" />
      <el-table-column label="序号" type="index" fixed="left" width="60" />
      <el-table-column label="采购事项名称" prop="planName" />
      <el-table-column label="采购事项编号" prop="planNo" />
      <!-- 采购类型：SERVICE/EQUIPMENT/NGINEERING/MATERIAL/DIRECT/MINOR -->
      <el-table-column label="采购需求类型" prop="purchaseType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PURCHASE_TYPE" :value="scope.row.purchaseType" />
        </template>
      </el-table-column>
      <el-table-column label="预算归属部门" prop="budgetDepartmentId">
        <template #default="scope"> {{ filterDept(scope.row.budgetDepartmentId) }} </template>
      </el-table-column>
      <el-table-column label="需求使用部门" prop="applicationDepartmentId">
        <template #default="scope"> {{ filterDept(scope.row.applicationDepartmentId) }} </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:purchase-plan:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:purchase-plan:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PurchaseEngineeringDetailForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { PurchasePlanApi } from '@/api/erp/purchase/plan'
import { getDeptPage, DeptVO, getSimpleDeptList } from '@/api/system/dept'
import PurchaseEngineeringDetailForm from './PurchaseEngineeringDetailForm.vue'

/** 工程采购计划明细 列表 */
defineOptions({ name: 'PurchaseEngineeringDetail' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  planName: undefined,
  purchaseType: undefined,
  budgetDepartmentName: undefined,
  applicationDepartmentId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PurchasePlanApi.getPurchasePlanPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取部门列表 */
const DeptPageList = ref<DeptVO[]>([])
const getDeptPageApi = async () => {
  try {
    const data = await getSimpleDeptList()
    DeptPageList.value = data
  } finally {
  }
}
const filterDept = (id) => {
  const targetDept = DeptPageList.value.find((dept) => {
    return dept.id == id
  })
  return targetDept?.name || ''
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PurchasePlanApi.delPurchasePlan(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除按钮操作 */
const handleDeleteList = async (ids: number[]) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PurchasePlanApi.deletePurchasePlanList(ids)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
  } catch {}
}

/** 选中操作 */
const selectionList = ref([])
const handleSelectionChange = (rows: any) => {
  selectionList.value = rows
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PurchasePlanApi.exportPurchasePlan(queryParams)
    download.excel(data, '采购计划明细.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getDeptPageApi()
})
</script>
